from typing import List, Optional

from sqlalchemy import select, and_
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from app.models.resource import Resource
from app.admin.schemas.resource import ResourceCreate, ResourceUpdate


async def create_resource(db: AsyncSession, resource: ResourceCreate) -> Resource:
    """创建资源"""

    db_resource = Resource(
        id=resource.id,
        name=resource.name,
        code=resource.code,
        type=resource.type,
        path=resource.path,
        method=resource.method,
        description=resource.description,        
        sort_order=resource.sort_order,
        tenant_id=resource.tenant_id
    )
    db.add(db_resource)
    await db.commit()
    await db.refresh(db_resource)
    return db_resource


async def get_resource_by_id(db: AsyncSession, resource_id: str) -> Optional[Resource]:
    """根据ID获取资源"""
    result = await db.execute(
        select(Resource)
        .where(Resource.id == resource_id)
    )
    return result.scalar_one_or_none()


async def get_resource_by_code(db: AsyncSession, code: str) -> Optional[Resource]:
    """根据代码获取资源"""
    result = await db.execute(
        select(Resource)
        .where(Resource.code == code)
    )
    return result.scalar_one_or_none()


async def get_resource_by_name(db: AsyncSession, name: str) -> Optional[Resource]:
    """根据名称获取资源"""
    result = await db.execute(
        select(Resource)
        # .options(selectinload(Resource.permissions))
        .where(Resource.name == name)
    )
    return result.scalar_one_or_none()


async def get_resources(
    db: AsyncSession,
    skip: int = 0,
    limit: int = 100,
    type: Optional[str] = None,
) -> List[Resource]:
    """获取资源列表"""
    query = select(Resource).options()
    
    # 添加过滤条件
    conditions = []
    if type:
        conditions.append(Resource.type == type)    
    if conditions:
        query = query.where(and_(*conditions))
    
    # 排序
    query = query.order_by(Resource.sort_order, Resource.id)
    
    # 分页
    query = query.offset(skip).limit(limit)
    
    result = await db.execute(query)
    return result.scalars().all()


async def update_resource(db: AsyncSession, resource_id: str, resource_update: ResourceUpdate) -> Resource:
    """
    更新资源信息
    """
    db_resource = await get_resource_by_id(db, resource_id)
    if not db_resource:
        return None


    update_data = resource_update.model_dump(exclude_unset=True)

    for key, value in update_data.items():
        setattr(db_resource, key, value)

    await db.commit()
    await db.refresh(db_resource)
    return db_resource


async def delete_resource(db: AsyncSession, resource_id: str) -> bool:
    """
    删除资源
    """
    db_resource = await get_resource_by_id(db, resource_id)
    if not db_resource:
        return False

    await db.delete(db_resource)
    await db.commit()
    return True
